﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using QBZ.Evaluation.Models;
using System;
using System.Threading.Tasks;

namespace QBZ.Evaluation.Domains.Permissions
{
    public class PermissionFilter : Attribute, IAsyncAuthorizationFilter
    {
        public PermissionFilter(UserLevel level)
        {
            Level = level;
        }
        public UserLevel Level { get; set; }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var authorizationSerive = context.HttpContext.RequestServices.GetRequiredService<IAuthorizationService>();
            var authorizationResult = await authorizationSerive.AuthorizeAsync(context.HttpContext.User, null, new PermissionAuthorizationRequirement (Level));
            if (!authorizationResult.Succeeded)
            {
                //var res = new ResponseModel(ErrReason.AccessDenied);
                context.Result = new ForbidResult();
                //context.Result = new JsonResult(res);
            }
        }
    }
}